<?php
/*
This sends a little bit of JSON to say if the user is logged in. 
*/

require_once( 'core.php' );
require_once( 'current_user_api.php' );

auth_ensure_user_authenticated( );
//helper_begin_long_process( );

$t_plugin_path = config_get( 'plugin_path' );
require_once( $t_plugin_path . 'DataRefine' . DIRECTORY_SEPARATOR . 'HTTPclient.php' );



$refineBaseURI = plugin_config_get( 'refineBaseURI' );
$authHashPrefix = plugin_config_get( 'authHashPrefix' );



# extracts the user information for the currently logged in user
# and prefixes it with u_
$f_user_id = gpc_get_int( 'id', auth_get_current_user_id() );
$row = user_get_row( $f_user_id );

extract( $row, EXTR_PREFIX_ALL, 'u' );
$u_email = user_get_email( $u_id );
$u_realname = user_get_realname( $u_id );
$t_project_id = helper_get_current_project();



if(!isset($_GET["grSession"])){
	$sessionID = false;
	$authorized = false;
}
else{
	$sessionID = $_GET["grSession"]; 
	$authorized = sha1($authHashPrefix.$sessionID); //secure way of sending authorization, without revealing password prefix.
}


$message = array("authorized" => $authorized,
		 "sessionID" => $sessionID,
		 "userName" =>  $u_username,
		 "userID" => $f_user_id,
		 "issuesProjectID" => $t_project_id
		 );

if($authorized != false){
	//post the message saying user is authorized to the Google Refine server
	
	$HTTPclient = new HTTPclient;
	
	$HTTPclient->refineBaseURI = $refineBaseURI;
	$HTTPclient->postActionURI = "/login-check-ok";
	$HTTPclient->authorized = $authorized;
	$HTTPclient->message = $message; //json data as a string
	$HTTPclient->postData(); //send the post!
	
	
	if($HTTPclient->success != false){
		$message["refineOK"] = true;
		$responseMessage = json_decode($HTTPclient->responseData, true);
		$message["refineRespose"] = $responseMessage;
	}
	else{
		$message["refineOK"] = false;
		$message["error"] = $HTTPclient->errorMessage;
	}

}

$output = json_encode($message, 1);

//now output for AJAX call from the Refine Login Screen
if(!isset($_GET["callback"])){
	header('Content-Type: application/json; charset=utf8');
	echo $output;
}
else{
	header('Content-Type: application/json; charset=utf8');
	$callback = $_GET["callback"];
	echo $callback."(".$output.");";
}


?>
